<?php

@header('Content-Type:application/json;charset=utf-8');
error_reporting(0);

require_once __DIR__ . '/ly/common.php';

$conf        = require_once __DIR__ . '/config.php';
$verify_conf = $conf['verify'];

$c     = r('c', '');
$id    = r('id', '');
$pwd   = r('pwd', '');
$page  = r('page', 1);
$name  = r('name', '');
$desc  = r('desc', '');
$isdir = r('isdir', 1);

use ly\Verify;
use ly\Lanzou;

if ($c === 'verify') {
	Verify::create($verify_conf);
	exit();
}

Lanzou::config($conf);

$ret = msg(-3, '未知操作');

switch ($c) {
	case 's':
		if ($id === '') $ret = msg(-1, '分享id不能为空');
		else $ret = Lanzou::share_direct_url($id, @$pwd);
		break;
	case 'list':
		if (preg_match('/^[bi]/', $id))
			$ret = Lanzou::share_list($id, $pwd, $page);
		else
			$ret = Lanzou::file_list($id, $pwd, $page);
		break;
	case 'upload':
		$ret = Lanzou::upload($id, $_FILES);
		break;
	case 'info':
		if ($id === '') $ret = msg(-1, '文件(夹)id不能为空');
		else $ret = Lanzou::info($id, $isdir);
		break;
	case 'rename':
		if ($id === '') $ret = msg(-1, '文件夹id不能为空');
		else if ($name === '') $ret = msg(-1, '名称不能为空');
		else $ret = Lanzou::rename($id, $name, $desc);
		break;
	case 'desc':
		if ($id === '') $ret = msg(-1, '文件id不能为空');
		else $ret = Lanzou::desc($id, $desc);
		break;
	case 'folder':
		if ($name === '') $ret = msg(-1, '文件夹名称不能为空');
		else $ret = Lanzou::create_folder($id, $name, $pwd, $desc);
		break;
	case 'move':
		$file_id = r('file_id', []);
		if ($file_id === '') $ret = msg(-1, '文件id不能为空');
		else $ret = Lanzou::move($id, ...$file_id);
		break;
	case 'delete':
		$file_id   = r('file_id', '');
		$folder_id = r('folder_id', '');
		if ($file_id === '' && $folder_id === '') $ret = msg(-1, '文件(夹)id不能为空');
		else $ret = Lanzou::delete(['file_id' => $file_id, 'folder_id' => $folder_id]);
		break;
	case 'login':
		$code = r('code', '');
		$pass = r('pass', '');
		if ($code === '')
			$ret = msg(-1, '图形验证码不能为空');
		else if (true !== $check = Verify::check($code, $verify_conf))
			$ret = msg(-2, $check);
		else if ($pass === '')
			$ret = msg(-3, '管理员密码不能为空');
		else
			$ret = Lanzou::login($pass);
		break;
	case 'logout':
		$ret = Lanzou::logout();
		break;
	case 'pwd':
		if ($id === '') $ret = msg(-1, '文件(夹)id不能为空');
		else $ret = Lanzou::set_pwd($id, $pwd, $isdir);
		break;
	default:
		if ($id === '') break;
		$first = strtolower(substr($id, 0, 1));
		if ($first === 'b')
			$ret = Lanzou::share_list($id, $pwd, $page);
		else if ($first === 'i')
			$ret = Lanzou::share_direct_url($id, $pwd);
		else
			$ret = Lanzou::direct_url($id);
}

exit(arr2json($ret));